package service

import (
	"context"
	"dy/internal/api/store"
	"dy/internal/models"
	"dy/pkg/util"
	"errors"
)

type MessageSrv interface {
	Action(ctx context.Context, param map[string]interface{}) error
	List(ctx context.Context, userId, toUserId int) ([]map[string]interface{}, error)
}

type messageService struct {
	store store.Factory
}

func (u *messageService) Action(ctx context.Context, param map[string]interface{}) error {
	var dyUserRelation *models.DyMessage
	err := util.StructTo(&param, &dyUserRelation)
	if err != nil {
		return err
	}

	if param["action_type"].(int) == 1 {
		_, err = u.store.Message().Create(ctx, dyUserRelation)
		if err != nil {
			return err
		}
	} else {
		return errors.New("wrong action_type")
	}

	return nil
}

func (u *messageService) List(ctx context.Context, userId, toUserId int) ([]map[string]interface{}, error) {
	result := make([]map[string]interface{}, 0)

	search := map[string]interface{}{}
	search["accept_id"] = userId
	search["send_id"] = toUserId
	list, _, err := u.store.Message().Find(ctx, search, "add_time", "")
	if err != nil {
		return nil, err
	}

	for _, element := range list {
		message := map[string]interface{}{
			"id":            element.Id,
			"content":       element.Content,
			"creative_time": element.AddTime,
		}

		result = append(result, message)
	}

	search["accept_id"] = toUserId
	search["send_id"] = userId
	list, _, err = u.store.Message().Find(ctx, search, "add_time", "")
	if err != nil {
		return nil, err
	}

	for _, element := range list {
		message := map[string]interface{}{
			"id":            element.Id,
			"content":       element.Content,
			"creative_time": element.AddTime,
		}

		result = append(result, message)
	}

	return result, nil
}

func NewMessageService(s *service) MessageSrv {
	return &messageService{
		store: s.store,
	}
}
